#include "HomeDirectorySortProxy.h"

#include <QFileSystemModel>

HomeDirectorySortProxy::HomeDirectorySortProxy(QStringList hidden_names)
    : QSortFilterProxyModel(nullptr)
    , _hidden_names(hidden_names)
    , _search_name("")
{
}

bool HomeDirectorySortProxy::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
    QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());

    QFileInfo lfi = fsm->fileInfo(left);
    QFileInfo rfi = fsm->fileInfo(right);

    if (lfi.isDir() != rfi.isDir())
        return lfi.isDir();

    return lfi.fileName() < rfi.fileName();
}

bool HomeDirectorySortProxy::filterAcceptsRow(int sourceRow, const QModelIndex & sourceParent) const
{
    bool parent_accepted = QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);

    if (parent_accepted && sourceParent.isValid()) {
        QModelIndex index0      = sourceModel()->index(sourceRow, 0, sourceParent);
        QString     q_file_name = sourceModel()->data(index0).toString();
        QFileSystemModel * fsm  = qobject_cast<QFileSystemModel *>(sourceModel());
        QFileInfo          fi   = fsm->fileInfo(index0);

        if (fi.absoluteFilePath().contains(fsm->rootPath()) && fi.absoluteFilePath().length() > fsm->rootPath().length()) {
            for (const auto & hidden : _hidden_names)
                if (q_file_name == hidden)
                    return false;
    
            if (!fi.isDir() && !q_file_name.contains(_search_name, Qt::CaseInsensitive))
                return false;
        }
    }

    return parent_accepted;
}
